package com.opennews.openplatform.service;

import com.opennews.openplatform.entity.tables.records.BankRecord;
import com.opennews.openplatform.jooq.DSLContextWrapper;
import com.opennews.openplatform.myspringbootcore.util.SharedUtil;
import lombok.RequiredArgsConstructor;
import org.jooq.DSLContext;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.opennews.openplatform.entity.Tables.BANK;


@RequiredArgsConstructor
@Service
public class BankService {
    private final DSLContext dslContext;
    private final DSLContextWrapper dslContextWrapper;
    private final Environment env;

    /**
     * Prepares the initial data for Bank and BankCard.
     */
    public void init() {
        if (dslContextWrapper.count(BANK) == 0) {
            List<BankRecord> records = new ArrayList<>();
            records.add(createRecord("上海银行", "BOSC"));
            records.add(createRecord("建行", "CCB"));
            records.add(createRecord("交行", "BCM"));
            records.add(createRecord("招行", "CMB"));
            dslContext.batchInsert(records);
        }
    }

    /**
     * Gets bank logo url based on its short name.
     *
     * @param shortName: The bank short name.
     * @return The full url of the bank logo.
     */
    String getLogoUrl(String shortName) {
        return !SharedUtil.isNullOrEmpty(shortName) ? String.format("%s%s/%s.png",
                env.getProperty("resource.httpBaseUrl"),
                env.getProperty("resource.bankLogoUrl"),
                shortName.toLowerCase()) : null;
    }

    /**
     * Queries all banks with basic info.
     *
     * @return List of map instance which contains keys below.
     * id: String of bank id.
     * name: String of bank name.
     * shortName: String of bank short name.
     */
    public List<Map<String, Object>> queryAllWithBasicInfo() {
        return dslContext.select(
                        BANK.ID.as("id"),
                        BANK.NAME.as("name"),
                        BANK.SHORT_NAME.as("shortName")
                ).from(BANK)
                .fetch()
                .map(p -> {
                    Map<String, Object> item = p.intoMap();
                    item.put("logoUrl", getLogoUrl(item.get("shortName").toString()));

                    return item;
                });
    }

    private BankRecord createRecord(String name, String shortName) {
        BankRecord record = dslContext.newRecord(BANK);
        record.setName(name);
        record.setShortName(shortName);

        return record;
    }
}
